package com.mijie.tag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.mijie.core.ApplicationProperties;
import com.mijie.util.Helper;

public class SelectTag extends SimpleTagSupport{
	private String id;
	private String category;
	private String name;
	private String value;
	private String title;
	
	public void doTag() throws JspException, IOException {
		Map<String,String> map = ApplicationProperties.getXmlConf(category);
		if(map==null || map.isEmpty()) return;
		List<String> keys = new ArrayList<String>();
		keys.addAll(map.keySet());
		Collections.sort(keys, new Comparator<String>(){
			@Override
			public int compare(String num1, String num2) {
				int diff = 0;
				if(Helper.isInt(num1) && Helper.isInt(num2))
					diff =  Integer.parseInt(num1)-Integer.parseInt(num2);
				return diff;
			}
			
		});
		JspWriter out = getJspContext().getOut();
		out.write("<select "+(id==null?"":"id='"+id+"'")+" "+(name==null?"":"name='"+name+"'")+" >");
		if(title!=null){
			if(value.trim().isEmpty())
				out.write("<option value='-999'>"+title+"</option>");
			else
				out.write("<option value='-999' selected='selected'>"+title+"</option>");
		}	
		
		for(Object key : keys){
			if(value==null || value.trim().isEmpty())
				out.write("<option value='"+key+"'>"+map.get(key)+"</option>");
			else
				out.write("<option value='"+key+"'"+(value.equals(key)?"selected='selected'" : "")+">"+map.get(key)+"</option>");
		}
		out.write("</select>");
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public void setTitle(String title) {
		this.title = title;
	}
	
}
